package pkg

import (
	"fmt"
	"github.com/dgrijalva/jwt-go"
	"time"
)

const (
	APP_KEY = "www.topgoer.com"
)

// TokenHandler 生成JWT
func TokenHandler(userId string) (string, error) {
	token := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{
		"userId": userId,
		"exp":    time.Now().Add(time.Hour * time.Duration(1)).Unix(),
		"iat":    time.Now().Unix(),
	})
	tokenString, err := token.SignedString([]byte(APP_KEY))
	return tokenString, err
}
func GetToken(tokenString string) (jwt.MapClaims, string) {
	token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {
		return []byte(APP_KEY), nil
	})
	if err != nil {
		if ve, ok := err.(*jwt.ValidationError); ok {
			if ve.Errors&jwt.ValidationErrorMalformed != 0 {
				fmt.Println("That's not even a token")
				return nil, "登录异常"
			} else if ve.Errors&(jwt.ValidationErrorExpired|jwt.ValidationErrorNotValidYet) != 0 {
				fmt.Println("Timing is everything")
				return nil, "登录过期"
			} else {
				fmt.Println("Couldn't handle this token:", err)
				return nil, "登录异常"
			}
		} else {
			fmt.Println("Couldn't handle this token:", err)
			return nil, "登录异常"
		}
	}

	if claims, ok := token.Claims.(jwt.MapClaims); ok && token.Valid {
		return claims, ""
	} else {
		fmt.Println("Invalid token claims")
		return nil, "登录异常"
	}
}
